$(function () {
    // 获得商品id
    // id在 url的search
  
    let id = location.search.split('=')[1];
  
    $.ajax({
      type: "get",
      url: "../interface/getItem.php",
      data: { id },
      dataType: "json"
    }).then(res => {
  
      let pic = JSON.parse(res.picture);
      
      let template = `
      <tr>
      <td>
          <input type="checkbox" class="allcheck">全选
      </td>
      <td colspan="2">商品名称</td>
      <!-- <td></td> -->
      <td>单价</td>
      <td>数量</td>
      <td>小计</td>
      <td>操作</td>
  </tr>
      <tr class="trs">
      <td><input type="checkbox" class="check"></td>
      <td colspan="2">
          <img src="./${pic[7].src}" alt="">	
         <b> ${res.title} 8GB+128GB 亮黑</b>
      </td>
      
      <td>${res.price}元</td>
      <td>
          <div>
              <span class="iconfont icon-jianhao minus"></span>
              <input type="number" value="1" max="${res.num}" min="1" class="num">

           <span class="iconfont icon-jiahao plus"></span>
          </div>
      </td>
      <td style="color: #FF5C00;">${res.price}元</td>
      <td class="lasttd">
                  <span class="iconfont icon-cuohao guanbi"></span>
      </td>
      <script>
        $(function () {
      const items = $('.check');
      const allcheck = $('.allcheck');

      allcheck.on('click', function () {
        items.prop('checked', $(this).prop('checked'));
      });

      function isAllCheck() {
        const elms = Array.from(items);
        return elms.every(el => $(el).prop('checked'));
      }

      items.on('click', function () {
        allcheck.prop('checked', isAllCheck());
      });
     });
</script>
      `;
      $('.five').html(template);

    

      // ---------------------
      // 事件写这
      $('.plus').on('click', function () {
        add(res.id, $('#num').val());
      });
    }).catch(xhr => {
      console.log(xhr);
    });
  });
  
  function add(id, num) {
    let product = { id, num };
  
    let shop = cookie.get('shop'); // 从cookie中获取数据
  
    if (shop) { // 判断cookie中是否有数据
      // 有数据则获得一个JSON字符串
      // 转成对象
      shop = JSON.parse(shop);
  
      // 判断当前商品的id在cookie数据中是否已经存在 如果已经存在则修改数量 不添加数据
      if (shop.some(el => el.id == id)) {
        let index = shop.findIndex(elm => elm.id == id); // 找到当前商品的索引
        let count = parseInt(shop[index].num); // 获得当前商品的数量
        count += parseInt(num);
        shop[index].num = count;
      } else { // 当前商品id在cookie数据中不存在 添加数据
        shop.push(product);
      }
  
    } else { // 没有获得cookie数据时 初始化成一个数组 然后添加数据
      shop = [];
      shop.push(product);
    }
  
    cookie.set('shop', JSON.stringify(shop));
  }